package com.capacitydorm.server.web;

import com.capacitydorm.server.common.vo.Result;
import com.capacitydorm.server.domain.Tower;
import com.capacitydorm.server.service.HouseService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/house")
public class HouseController {

    @Resource
    private HouseService houseService;

    /**
     * 查询所有楼
     * @return
     */
    @GetMapping
    public ResponseEntity<List<Tower>> selectAll(){
        try {
                List<Tower> list = houseService.selectAll();
            return new ResponseEntity<>(list,HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 添加楼
     */
    @PostMapping()
    public ResponseEntity<Result> addTower(Tower tower){
        try{
          List<Tower> list =  houseService.check(tower);
          if (list.size() != 0){
              return  new ResponseEntity<>(new Result(500,"楼名重复"),HttpStatus.INTERNAL_SERVER_ERROR);
          }
            houseService.add(tower);
            return  new ResponseEntity<>(new Result(201,null),HttpStatus.CREATED);
        }catch (Exception e){
            e.printStackTrace();
            return  new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }
    /**
     * 删除楼
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTower(@PathVariable("id") Integer id){
        try {
            houseService.delete(id);
            return new ResponseEntity<>(HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return  new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }
    /**
     *  修改楼
     */
    @PutMapping("/{id}")
    public ResponseEntity<Void> updateTower(@PathVariable("id") Integer id,Tower tower){
        try{
            houseService.update(id,tower);
            return new ResponseEntity<>(HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


}
